/*
 * @Author: fisher
 * @Date: 2020-02-20 11:24:54
 * @LastEditTime: 2020-05-15 19:42:42
 * @LastEditors: your name
 * @Description:
 * @FilePath: /assessment/src/utils/utils.ts
 * @可以输入预定的版权声明、个性签名、空行等
 */
interface Obj {
  [key: string]: any
}
/**
 * 生成UUID
 * @param len 长度
 * @param radix 进制
 */
function uuid(len: number = 32, radix: number = 16): string {
  const chars =
    '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  let i
  radix = radix || chars.length

  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)]
  } else {
    let r
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
    uuid[14] = '4'

    // Fill in random data.  At i==19 set the high bits of clock sequence as
    // per rfc4122, sec. 4.1.5
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16)
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r]
      }
    }
  }

  return uuid.join('')
}
/**
 * 获取数据类型
 * @param type
 */
function getType(type: string) {
  return function <T>(value: T): boolean {
    return Object.prototype.toString.call(value) === '[object ' + type + ']'
  }
}
const isObject = getType('Object')
/**
 *  格式化 query 成 obj
 * @param str user=111&n=*** (传：window.location.search.slice(1))
 * @param encode true or false
 */
function queryToJson(str: string, encode: boolean = false): Obj {
  if (!str) {
    return {}
  }
  const param = str.split('&')
  const obj: Obj = {}
  param.forEach((item) => {
    const items = item.split('=')
    const key = items[0]
    if (key) {
      obj[key] = items[1]
        ? encode
          ? decodeURIComponent(items[1])
          : items[1]
        : ''
    }
  })
  return obj
}
/**
 * 补零
 * @param num
 * @returns {string}
 */
function pad(num: number): string {
  return new Array(2 - num.toString().length + 1).join('0') + num
}
/**
 * object 转 formData
 * @param target {}
 */
function objectToFormData(target: Obj): FormData {
  const formData = new FormData()
  Object.keys(target).forEach((key) => {
    formData.append(key, target[key])
  })
  return formData
}
/**
 * copyText 粘贴板
 * @param text 要复制的文本
 */
function copyText(text: string): void {
  const tag = document.createElement('input')
  tag.setAttribute('id', 'cp_hgz_input')
  tag.setAttribute('style', 'position:absolute;top:0;left:0;opacity: 0')
  tag.value = text
  document.body.appendChild(tag)
  const input = document.getElementById('cp_hgz_input') as HTMLInputElement
  input.select()
  document.execCommand('copy')
  input.remove()
}
/**
 * 千分数
 * @param num 数字
 */
function formatNumber(num: number): string {
  const reg = /\d{1,3}(?=(\d{3})+$)/g
  return (num + '').replace(reg, '$&,')
}
/**
 * base64 转 file
 * @param data
 * @param filename
 */
function baseDataToFile(
  data: any,
  filename: string = 'img_' + Date.now()
): File {
  const arr = data.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  // 转换成file对象
  return new File([u8arr], filename, { type: mime })
  // 转换成成blob对象
  // return new Blob([u8arr],{type:mime});
}
function getDeviceType(): string {
  let name = 'pc'
  const u = navigator.userAgent
  if (u.includes('Android') || u.includes('Adr')) {
    name = 'android'
  }
  if (u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    name = 'ios'
  }
  return name
}
export {
  uuid,
  queryToJson,
  pad,
  objectToFormData,
  copyText,
  formatNumber,
  isObject,
  baseDataToFile,
  getDeviceType
}
